const http = require('/util/request');
const util = require('/util/util');
App({
  http,
  util,
  onLaunch: function (opts) {
     let _self = this;
     console.log("onLaunch")
  
     //自动获取openid 登录
      _self.autoLogin()
   
    //获取手机型号
    wx.getSystemInfo({
      success: res => {
        let modelmes = res.model;
        if (modelmes.search('iPhone X') != -1) {
          _self.globalData.isIphoneX = true
        }
        wx.setStorageSync('modelmes', modelmes)
      }
    })
    
  },
  onShow: function (opts) {
    console.log("app_onshow");
    var self = this;
    //删除分享信息
    if (opts.scene != 1007 && opts.scene != 1008) {
      wx.removeStorageSync("share")
    }
  
  },
  onHide: function () {
    //console.log('App Hide')
  },
  globalData: {
    isIphoneX: 0,
    code: null,  // 小程序code
    hasLogin: false, // false 未登录 true登录
    openid: null,
    unionId: null,
    session_key:null,
  
  },

  /*获取元素大小及位置 */
  getElementRect(select, callBack) {
    wx.createSelectorQuery().select(select).boundingClientRect(function (rect) {
      callBack && callBack(rect);
    }).exec();
  },
  /* 登录 */
  login(e, callback) {

    var self = this;
    if (e.detail.errMsg == 'getUserInfo:fail auth deny') {
      wx.showToast({
        title: '未授权不能操作',
        icon:'none'
      })
      return;
    }
    if(!self.globalData.openid){
      wx.showToast({
        title: 'openid不存在',
        icon:'none'
      })
      return;
    } 


          var userinfo = e.detail.userInfo? e.detail.userInfo:{};//用户信息
          var encryptedData = e.detail.encryptedData;
          var iv = e.detail.iv;          
          //请求登录接口
          http.loginUrlPost(
            {
              //code: self.globalData.code,
              encryptedData: encryptedData,
              XDEBUG_SESSION_START:17102,
              iv: iv,
              session_key:self.globalData.session_key,
              openid:self.globalData.openid,
              userinfo: JSON.stringify(userinfo)
            }
          ).then(function (res) {
            if (res.code == 0) {
              var userinfo = {
                token: res.token,
                hall_list:res.hall_list,
                avatar:res.avatar,
                nickname:res.nickname,
                uid:res.uid,
                mobile:res.phone,
              }
              wx.setStorageSync('userinfo', userinfo);
              callback(null, userinfo);
              wx.showToast({
                title: '登录成功',
                icon:'none'
              })
            }else{
              //清楚缓存
              wx.removeStorageSync('userinfo');
              //重新获取code
              self.getUserOpenId(function(succ,msg,res){});
              wx.showToast({
                title: '登录失败 请重试',
                icon:'none'
              })
              //callback(res.msg);
            }
          }).catch(err => {
            //callback("登录失败");
          })
  },
  //获取openid
  getUserOpenId: function (callback) {
    var self = this
      wx.login({
        success: function (data) {
          http.getUserOpenIdPost({
            code: data.code,
          }).then(function(res){
            if(res.code == 0){
              self.globalData.openid = res.data.openid
              self.globalData.session_key = res.data.session_key
              callback(1,'成功',res.data)
            }else{
              callback(0,'失败')
            }
          }).catch(err => {
            callback(0,err);
          })
        },
        fail: function (err) {
          callback(0,"获取code失败")
        }
      })
    
  },
  // 获取小程序code
  xcxCode: function () {
    wx.login({
      success: res => {
        this.globalData.code = res.code
        // console.log(res.code);
      },
      fail: function (err) {
        console.log('wx.login 接口调用失败，将无法正常使用开放接口等服务')
      }
    })
  },
  // 获取 厅角色
  getRoles: function (callback,falge = true) {

    if (!wx.getStorageSync('userinfo').token) {
       callback(false,"未登录", "");
       return;
    }
    if(!wx.getStorageSync('hall_info')){
      callback(false,"没有可以申请加入的厅", "");
      return;
    }
    var userinfo = wx.getStorageSync('userinfo')
    var token = userinfo.token
    var hall_id = wx.getStorageSync('hall_info').id
    console.log("角色接口token",token,"hall_id",hall_id);
    http.getRolePost({
      token,
      hall_id
    },falge).then(res => {
      if (res.code == 0) {
        callback(true, "成功", res);
      } else {
        callback(false,'接口失败',res);
      }
    }).catch(err => {
      callback(false,err);
    })
  },
  //
  // getUserInfoCallback(res,callback){
  //   callback(res)
  // }
   //自动获取openid 登录
   autoLogin(){
          var _self = this
          console.log(wx.getStorageSync("userinfo"),"用户信息")
          //用户信息不存在 获取openId
          _self.getUserOpenId(function(succ,msg,res){
            if(succ){
              //用户存在更新token
              if(wx.getStorageSync("userinfo")){
                if(res.userinfo && res.userinfo.token){
                  var userinfo = wx.getStorageSync("userinfo")
                  userinfo.token = res.userinfo.token
                  wx.setStorageSync('userinfo', userinfo);
                }
              }else{
                //永久登录
                if(res.userinfo && res.userinfo.token){
                  var userinfo = res.userinfo
                  userinfo.uid = res.userinfo.id
                  wx.setStorageSync('userinfo', userinfo);
                }
              }
              //如果userinfo不存在 wx.getStorageSync("userinfo")
              if(!res.userinfo && wx.getStorageSync("userinfo")){
                wx.removeStorageSync("userinfo")
              }
              // 所以此处加入 Callback 以防止这种情况
              if (_self.getUserInfoCallback) {
                _self.getUserInfoCallback(res)
              }
            }else{
              wx.showToast({
                title: 'openid获取失败',
                icon:'none'
              })
              console.log("openid获取失败")
            }  
      });
   }

})
